package com.ktjiaoyu.service.impl;

import com.ktjiaoyu.mapper.SysUserMapper;
import com.ktjiaoyu.pojo.SysUser;
import com.ktjiaoyu.service.SysUserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    RedisTemplate redisTemplate;

    @Cacheable(key = "'user::'+#id",value = "users")
    @Override
    public SysUser getUser(Long id) {
        return sysUserMapper.selectById(id);
    }

    @CachePut(key = "'user::'+#sysUser.getUsrId()",value = "users")
    @Override
    public SysUser addUser(SysUser sysUser) {
        sysUserMapper.insert(sysUser);
        return sysUser;
    }

    @CachePut(key = "'user::'+#sysUser.getUsrId()",value = "users")
    @Override
    public SysUser updateUser(SysUser sysUser) {
        sysUserMapper.updateById(sysUser);
        return sysUser;
    }

    @CacheEvict(key = "'user::'+#id",value = "users")
    @Override
    public void deleteUser(Long id) {
        sysUserMapper.deleteById(id);
    }

//    @Override
//    public SysUser getUser(Long id) {
//        //首先从redis中查询数据
//        System.out.println("===============从redis获得数据===============");
//        SysUser sysUser = (SysUser)redisTemplate.opsForValue().get("user::" + id);
//        //判断数据是否获取到
//        if(sysUser==null){//没有拿到
//            System.out.println("===============从mysql获得数据===============");
//            //从mysql中查询
//            sysUser=sysUserMapper.selectById(id);
//            //并且将数据保存到redis中
//            redisTemplate.opsForValue().set("user::" + id,sysUser);
//        }
//        return sysUser;
//    }
}
